package kbpost

import (
	"context"
	"strconv"

	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetEntrySectionRelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetEntrySectionRelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetEntrySectionRelListLogic {
	return &GetEntrySectionRelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetEntrySectionRelListLogic) GetEntrySectionRelList(in *blog.GetEntrySectionRelReq) (*blog.GetEntrySectionRelResp, error) {
	if len(in.Ids) == 0 || in.Type == nil || *in.Type == 0 {
		return &blog.GetEntrySectionRelResp{}, nil
	}
	var ids []any
	for _, v := range in.Ids {
		ids = append(ids, v)
	}
	filterMap := make(map[string]map[string][]any)
	//1:香水查品牌、气味家族、调香师
	if *in.Type == 1 {
		filterMap[model.BlogKnowledgeBaseRelationshipColumns.FromEntryID] = map[string][]any{
			"in": ids,
		}
		filterMap[model.BlogKnowledgeBaseRelationshipColumns.ToSectionID] = map[string][]any{
			"in": {14, 16, 18},
		}
	} else { //2:品牌、气味家族、调香师  查香水
		filterMap[model.BlogKnowledgeBaseRelationshipColumns.ToEntryID] = map[string][]any{
			"in": ids,
		}
		filterMap[model.BlogKnowledgeBaseRelationshipColumns.FromSectionID] = map[string][]any{
			"equalTo": {15},
		}
	}

	list, _, err := l.svcCtx.KBEntry.GetRelationshipList(l.ctx, model.M{}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}
	var data = make(map[uint64]string)
	if len(list) > 0 {
		//商品=[品牌，调香师，气味]
		if *in.Type == 1 {
			var idMap = make(map[uint64]struct{})
			for _, v := range list {
				if v.ToEntryID > 0 {
					if _, ok := idMap[v.ToEntryID]; !ok {
						idMap[v.ToEntryID] = struct{}{}
						data[v.FromEntryID] += strconv.FormatInt(int64(v.ToEntryID), 10) + ","
					}
				}
			}
		} else { //气味=[香水，香水，香水]  品牌=[香水，香水，香水]
			var idMap = make(map[uint64]struct{})
			for _, v := range list {
				if v.FromEntryID > 0 {
					if _, ok := idMap[v.FromEntryID]; !ok {
						idMap[v.FromEntryID] = struct{}{}
						data[v.ToEntryID] = strconv.FormatInt(int64(v.FromEntryID), 10) + ","
					}
				}
			}
		}
	}
	if len(data) > 0 {
		for i, v := range data {
			data[i] = v[0 : len(v)-1]
		}
	}
	return &blog.GetEntrySectionRelResp{
		Data: data,
	}, nil
}
